package com.google.code.ptrends.common.utils;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Collection;

import org.codehaus.jackson.JsonFactory;
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.JsonParser;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.MappingIterator;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.ObjectWriter;
import org.codehaus.jackson.map.SerializationConfig;

import com.google.code.ptrends.common.entities.Item;
import com.google.code.ptrends.common.entities.Session;

public class JsonHelper {

	public void serialize(final Item item, final OutputStream stream)
			throws JsonGenerationException, JsonMappingException, IOException {
		final ObjectMapper mapper = new ObjectMapper();
		final ObjectWriter writer = mapper.writerWithDefaultPrettyPrinter();
		writer.writeValue(stream, item);
	}

	public Collection<Item> loadItems(final String fileName)
			throws JsonParseException, FileNotFoundException, IOException {

		final Collection<Item> listETLItem = new ArrayList<Item>();

		final ObjectMapper mapper = new ObjectMapper();
		mapper.configure(SerializationConfig.Feature.WRITE_DATES_AS_TIMESTAMPS,
				false);
		final JsonFactory factory = new JsonFactory();
		InputStream inputStream = null;

		try {
			inputStream = new FileInputStream(fileName);
			final JsonParser parser = factory.createJsonParser(inputStream);

			final MappingIterator<Item> iterator = mapper.readValues(parser,
					Item.class);
			while (iterator.hasNext()) {
				final Item itemi = iterator.next();
				listETLItem.add(itemi);
			}
		} finally {
			if (inputStream != null) {
				inputStream.close();
			}
		}

		return listETLItem;
	}

	public Collection<Session> loadSessions(final String fileName)
			throws JsonParseException, FileNotFoundException, IOException {

		final Collection<Session> listSessions = new ArrayList<Session>();

		final ObjectMapper mapper = new ObjectMapper();
		mapper.configure(SerializationConfig.Feature.WRITE_DATES_AS_TIMESTAMPS,
				false);
		final JsonFactory factory = new JsonFactory();
		InputStream inputStream = null;

		try {
			inputStream = new FileInputStream(fileName);
			final JsonParser parser = factory.createJsonParser(inputStream);

			final MappingIterator<Session> iterator = mapper.readValues(parser,
					Session.class);
			while (iterator.hasNext()) {
				final Session session = iterator.next();
				listSessions.add(session);
			}
		} finally {
			if (inputStream != null) {
				inputStream.close();
			}
		}
		return listSessions;
	}

}
